<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import { putDelayMessageApi} from '@/apis/task'
// 原定计划时间
const planDepartureTime = ref('')
// 任务id
const taskId = ref('')
// 日期选择器选择的时间
const selectTime = ref('')
// 当前的日期时间
const nowDay = ref('')
// 延迟原因的txt
const delayText = ref('')
// 当前完整时间
const nowTime = ref('')
// 时间选择器选择的完整时间
const nextTime = ref('')

// 判断选择时间是否延迟2小时内
const delayTime = computed(() => {
  nextTime.value = nowDay.value + ' ' + selectTime.value
  // 转换为时间戳
  const end = new Date(nextTime.value).getTime();
  const start = new Date(nowTime.value).getTime()
  // 判断大于0且小于2小时
  return (end - start) >= 0 && (end - start) <= (7200 * 1000)
})
// 输入框的字数
const delayTextCount = computed(() => {
  return delayText.value.length
})
// 判断输入框的字数是否符合要求
const textCountFlag = computed(() => {
  return delayText.value.length>0 && delayText.value.length<=50
})
// 提交按钮的判断
const submitButton = computed(() => {
  return delayTime.value && textCountFlag.value
})



onLoad((params) => {
  planDepartureTime.value = params.planDepartureTime
  nowTime.value = params.planDepartureTime
  nowDay.value = nowTime.value.split(' ')[0]
  taskId.value = params.id
})
// 得到日期选择器的方法
const getTime = (e) => {
  selectTime.value = e.detail.value
}

// 点击提交按钮提交
const onFormSubmit = async() => {
  const form = {
    delayReason : delayText.value,
    delayTime : nowDay.value + ' ' + selectTime.value,
    id: taskId.value
  }
 const res = await putDelayMessageApi(form)
 if (res.code === 200) {
  uni.reLaunch({ url: '/pages/task/index' })
 } else {
  uni.utils.toast({title:'提交失败',type:'error'})
 }
}

</script>

<template>
  <view class="page-container">
    <uni-list :border="false">
      <uni-list-item title="原定时间 " showArrow :rightText="planDepartureTime" />
      <uni-list-item title="延迟时间" showArrow>
        <template v-slot:footer>
          <picker @change="getTime" class="time-picker" mode="time">
            <text v-if="!selectTime">不可超过2个小时</text>
            <text v-else :class="{ error: !delayTime }">{{ nowDay + ' ' + selectTime + ':00' }}</text>
          </picker>
        </template>
      </uni-list-item>
      <uni-list-item direction="column">
        <template v-slot:body>
          <view class="textarea-wrapper" >
            <textarea class="textarea"  placeholder-style="color: #818181" placeholder="请输入延迟提货原因"
              v-model="delayText"></textarea>
            <text class="words-count" :class="{error: delayTextCount>50}" >{{ delayTextCount }}/50</text>
          </view>
        </template>
      </uni-list-item>
      <uni-list-item :border="false">
        <template v-slot:body>
          <button @click="onFormSubmit" :disabled="!submitButton" class="button">提交</button>
        </template>
      </uni-list-item>
    </uni-list>
  </view>
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
